﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Collections;
using System.Web.Services;
using Catering_Rules;
using Microsoft.Office.Interop;
using Microsoft.Office.Core;
using System.IO;

namespace Catering.Catering_Page.Caipin
{
    public partial class caigou_Edit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string page = "1";
                if (Request.QueryString["page"] != null) page = Request.QueryString["page"].ToString();
                string searchtxt = "";
                if (Request.QueryString["SearchTxt"] != null) searchtxt = Request.QueryString["SearchTxt"].ToString();
                this.txt_Name.Text = searchtxt;
                int currentpage = 1;
                Int32.TryParse(page, out currentpage);
                Load_Data(currentpage);
            }
            this.txstattime.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy-MM-dd'})");
            this.txstoptime.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy-MM-dd',maxDate:'%y-#{%M+1}-%d'})");
        }

        //加载也没数据
        public void Load_Data(int page)
        {
            if (Request.QueryString["CGID"] == null) return;

            string Purchase_id = Request.QueryString["CGID"].ToString();
            this.HidCID.Value = Purchase_id;
            Catering_Model.Purchase md = new Catering_Rules.Purchase().GetModel(Convert.ToInt32(Purchase_id));
            DataTable dt = new Catering_Rules.Company().GetView_CompanyClass(md.temp1).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                this.lab_RNo.Text = dt.Rows[0]["BianHao"].ToString();
                this.lab_Vs.Text = dt.Rows[0]["Vs"].ToString();
                this.lab_Controlled.Text = dt.Rows[0]["Controlled"].ToString();
            }
            this.lab_Date.Text = md.Date.ToShortDateString();
            this.lab_BRid.Text = new Catering_Rules.T_Personnel().GetModel(Convert.ToInt32(md.BRid)).Name;
            this.HF_ClassID.Value = md.temp1;
            this.LoadRep(GetStrWhere(), page);
        }

        //获取虚拟列
        public int xuid = 0;
        public string GetindexXu()
        {
            xuid += 1;
            return ((this.AspNetPager1.CurrentPageIndex - 1) * this.AspNetPager1.PageSize + xuid).ToString();
        }
        //绑定Rep控件
        public void LoadRep(string strwhere, int page)
        {
            this.AspNetPager1.RecordCount = new Catering_Rules.PurchaseInfo().GetCountBywhere(strwhere);
            if (page > 0) this.AspNetPager1.CurrentPageIndex = page;
            DataTable dt_PurchaseInfo = new Catering_Rules.PurchaseInfo().GetList(this.AspNetPager1.PageSize, this.AspNetPager1.CurrentPageIndex - 1, strwhere + " order by id desc").Tables[0];//分页处理
            this.Rep_PurchaseInfo.DataSource = dt_PurchaseInfo;
            this.Rep_PurchaseInfo.DataBind();
        }

        //绑定Rep控件
        public void LoadRep(string strwhere)
        {
            LoadRep(strwhere, 0);
        }

        //添加一条数据
        protected void btn_tijiao_Click(object sender, EventArgs e)
        {
            Random rd = new Random();
            Catering_Model.PurchaseInfo md = new Catering_Model.PurchaseInfo();
            md.CID = Convert.ToInt32(Request.QueryString["CGID"].ToString());
            string strpinhao = this.txt_pinhao.Text.Trim();
            if (string.IsNullOrEmpty(strpinhao))
            {
                Response.Write("<script>alert('参数错误！'); history.go(-1);</script>");
                return;
            }
            DataTable dt_RawMaterial_Area = new Catering_Rules.RawMaterial_Area().GetList("InDBid='" + strpinhao + "'").Tables[0];

            decimal sum = 0;
            decimal.TryParse(this.txt_jhsl.Text, out sum);
            if (dt_RawMaterial_Area != null && dt_RawMaterial_Area.Rows.Count > 0)
            {
                Catering_Model.E_RawMaterial rm = GetRawMaterialInfo(dt_RawMaterial_Area.Rows[0]["RawID"].ToString());
                if (rm != null)
                {
                    md.DID = rm.id.ToString();
                    md.PName = rm.RAWName;

                    string unit = new Catering_Rules.Units().GetModel(Convert.ToInt32(rm.temp2)).UName;
                    bool iskg = true;
                    decimal guige = 1;
                    decimal UtilKg = Toolss.GetSpecifications(rm.id, unit, out iskg);
                    guige = iskg ? 1000 : 1;
                    decimal weight = Toolss.GetMathResult(UtilKg * sum, 2, 3);
                    md.temp1 = (weight * guige).ToString();
                }
                else
                {
                    md.DID = "";
                    md.PName = "";
                }
            }

            md.Specifications = this.txt_guige.Text;
            md.Company = this.txt_danweiid.Value;
            md.ProgramNumber = this.txt_jhsl.Text;
            md.Requirement = this.txt_xcgl.Text;
            md.FactNumber = this.txt_FactNumber.Text;
            md.Back = this.txt_bz.Text;

            new Catering_Rules.PurchaseInfo().Add(md);
            string url = GetCurrentUrl();
            Response.Redirect(url);
        }

        //导出Excel
        protected void But_OutPut_Purchase_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel.Application excel1 = null;
            Microsoft.Office.Interop.Excel.Workbooks books = null;
            Microsoft.Office.Interop.Excel.Workbook book = null;
            Microsoft.Office.Interop.Excel._Worksheet ws = null;
            int startrows = 1;
            int startcols = 1;
            int maxnum = 51;
            string stick = DateTime.Now.Ticks.ToString();
            try
            {
                excel1 = new Microsoft.Office.Interop.Excel.Application();
                excel1.Application.Workbooks.Add(true);//引用Excel工作簿
                excel1.Visible = false;
                books = (Microsoft.Office.Interop.Excel.Workbooks)excel1.Workbooks;
                book = books.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                ws = (Microsoft.Office.Interop.Excel.Worksheet)book.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                Dictionary<int, string> dc = new Dictionary<int, string>();
                dc = GetRawMaterials();
                string Strcid = this.HidCID.Value;
                int CID = 0;//表Purchase id，表PurchaseInfo CID
                Int32.TryParse(Strcid, out CID);
                if (CID <= 0) return;

                Catering_Model.Purchase md = new Catering_Rules.Purchase().GetModel(CID);
                Dictionary<string, DataTable> dt_ar = new Dictionary<string, DataTable>();//额外sheet添加
                Dictionary<string, string> raws_ar = new Dictionary<string, string>();//sheet内原料的ID
                string name = "";
                if (md != null && !string.IsNullOrEmpty(md.temp1))
                {
                    Catering_Model.ClassInfo class_md = new Catering_Rules.ClassInfo().GetModel(Convert.ToInt32(md.temp1));
                    if (class_md != null && class_md.CName != "") name = class_md.CName.Contains("班组") ? class_md.CName : (class_md.CName + "班组");
                }

                #region 判断是否存在特定规则

                if (md != null && !string.IsNullOrEmpty(md.temp1))
                {
                    Catering_Model.ClassInfo cmd = new Catering_Rules.ClassInfo().GetModel(Convert.ToInt32(md.temp1));
                    if (cmd != null && cmd.AID > 0)
                    {
                        string arids = new Catering_Rules.AreaRules().GetARIDsByAreaID(cmd.AID);
                        string[] SplitARIDs = arids.Split(',');
                        if (SplitARIDs.Length > 0)
                        {

                            foreach (string arid in SplitARIDs)
                            {
                                int id = 0;
                                Int32.TryParse(arid, out id);
                                if (id > 0)
                                {
                                    Catering_Model.AreaRules armd = new Catering_Rules.AreaRules().GetModel(id);
                                    dt_ar.Add(armd.ARName, CreateExcelTable());
                                    raws_ar.Add(armd.ARName, armd.RawIDs);
                                }
                            }
                        }
                    }
                }

                #endregion

                #region 筛选-特殊采购规则

                foreach (int id in dc.Keys)
                {
                    DataTable dt_PurchaseInfo = new Catering_Rules.PurchaseInfo().GetPuchaseListByRMID(CID, id);
                    //string name = dc[id];
                    if (dt_PurchaseInfo != null && dt_PurchaseInfo.Rows.Count > 0)
                    {
                        if (raws_ar.Count > 0)
                        {
                            foreach (string key in raws_ar.Keys)
                            {
                                string values = raws_ar[key];
                                DataRow[] temDr = dt_PurchaseInfo.Select(" DID IN(" + values + ")");
                                if (temDr != null && temDr.Length > 0)
                                {
                                    for (int i = 0; i < temDr.Length; i++)
                                    {
                                        int tempid = Convert.ToInt32(temDr[i]["id"]);
                                        string DID = temDr[i]["DID"].ToString();
                                        string PName = temDr[i]["PName"].ToString();
                                        string Company = temDr[i]["Company"].ToString();
                                        string Requirement = temDr[i]["Requirement"].ToString();
                                        string FactNumber = temDr[i]["FactNumber"].ToString();
                                        int RAWIDS = Convert.ToInt32(temDr[i]["RAWIDS"]);

                                        DataRow dr = dt_ar[key].NewRow();
                                        dr["CID"] = CID;
                                        dr["DID"] = DID;
                                        dr["PName"] = PName;
                                        dr["Company"] = Company;
                                        dr["Requirement"] = Requirement;
                                        dr["FactNumber"] = FactNumber;
                                        dt_ar[key].Rows.Add(dr);
                                        dt_PurchaseInfo.Rows.Remove(temDr[i]);
                                    }
                                }
                            }
                        }
                    }
                    if (dt_PurchaseInfo != null && dt_PurchaseInfo.Rows.Count > 0) GetPuchase_Excel01(ws, dt_PurchaseInfo, name, Strcid, ref startrows, ref startcols, maxnum);
                }

                #endregion

                #region 导出特殊规则表

                foreach (string key in dt_ar.Keys)
                {
                    DataTable tempdt = dt_ar[key];
                    //if (tempdt != null && tempdt.Rows.Count > 0) GetPuchase_Excel(book, tempdt, key, Strcid);
                    if (tempdt != null && tempdt.Rows.Count > 0) GetPuchase_Excel01(ws, tempdt, name, Strcid, ref startrows, ref startcols, maxnum);
                }

                #endregion

                #region 页面调整

                Microsoft.Office.Interop.Excel.Range canbie;//创建Range操作一行作为标题
                canbie = ws.get_Range(ws.Cells[1, 1], ws.Cells[startrows, 12]); //取得合并的区域
                canbie.Borders.LineStyle = 1;
                ws.Cells.EntireColumn.AutoFit();//宽度自适应

                ws.PageSetup.CenterHeader = name + "采购计划";
                ws.PageSetup.LeftFooter = "编制人/日期：";
                ws.PageSetup.CenterFooter = "审核人/日期：";
                ws.PageSetup.RightFooter = "批准人:";
                ws.PageSetup.PrintTitleColumns = "$A:$L";

                ws.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlPortrait; //设置为纵向打印
                //ws.PageSetup.PaperSize = Microsoft.Office.Interop.Excel.XlPaperSize.xlPaperA4;       //设置打印字为A4纸张
                //ws.PageSetup.PrintTitleRows = "$1:$3";
                //ws.PrintPreview(true);            //打印预览
                #endregion

                if (!Directory.Exists(Server.MapPath("../../xls_template"))) Directory.CreateDirectory(Server.MapPath("../../xls_template"));
                book.SaveAs(Server.MapPath("../../xls_template") + "\\" + stick + ".xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlAddIn8);
            }
            finally
            {
                if (excel1 != null)
                {
                    if (books != null)
                    {
                        if (book != null)
                        {
                            book.Close(false, null, null);
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
                            book = null;
                        }
                        books.Close();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
                        books = null;
                    }
                    excel1.Application.Workbooks.Close();
                    excel1.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel1);
                    Toolss.KillExcel(excel1);
                    excel1 = null;
                    GC.Collect();
                }
            }

            #region 发送

            try
            {
                string path = Server.MapPath("../../xls_template") + "\\" + stick + ".xls";
                System.IO.FileInfo file = new System.IO.FileInfo(path);
                Response.Clear();
                Response.Charset = "GB2312";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                // 添加头信息，,弹出另存为窗口  
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
                //让浏览器头显示下载信息  
                Response.AddHeader("Content-Length", file.Length.ToString());
                // 指定返回一个不能被客户端读取的流，下载  
                Response.ContentType = "application/ms-excel";
                //把文件流下载到客户端  
                Response.WriteFile(file.FullName);
                //Toolss.DeleteFile("../../xls_template/" + stick + ".xls");
                // 停止页面的执行
                Response.End();
            }
            catch { }

            #endregion

        }

        private void GetPuchase_Excel01(Microsoft.Office.Interop.Excel._Worksheet ws, DataTable dt_PurchaseInfo, string typeName, string cid, ref int startrows, ref int startcols, int maxnum)
        {
            #region 内容

            if (dt_PurchaseInfo != null && dt_PurchaseInfo.Rows.Count > 0)
            {
                for (int i = 0; i < dt_PurchaseInfo.Rows.Count; i++)
                {
                    int y = startrows % (maxnum + 3);
                    if (y == 1 && startcols == 1)
                    {
                        AddTitle(ws, startrows, cid);
                        startrows = startrows + 3;
                    }
                    else if (i == 0)
                    {
                        startrows++;
                    }
                    int xuhao = 0;
                    if (startrows % (maxnum + 3) == 0)
                    {
                        xuhao = startcols == 1 ? maxnum : maxnum * 2;
                    }
                    else
                    {
                        xuhao = startcols == 1 ? (startrows % (maxnum + 3)) - 3 : ((startrows % (maxnum + 3)) - 3) + maxnum;
                        //if (xuhao == maxnum + 1)
                        //{
                        //    startcols = 7;
                        //    startrows = startrows - maxnum;
                        //}
                        //if (xuhao == 1) startcols = 1;
                    }
                    string diama = this.Getpinhao(dt_PurchaseInfo.Rows[i]["DID"].ToString(), dt_PurchaseInfo.Rows[i]["CID"].ToString());
                    string pname = dt_PurchaseInfo.Rows[i]["PName"].ToString();
                    string xinghaoguige = this.GetRawGuiGe(dt_PurchaseInfo.Rows[i]["DID"].ToString());
                    string danwei = this.GetUnitName(dt_PurchaseInfo.Rows[i]["Company"].ToString());
                    string xushuliang = dt_PurchaseInfo.Rows[i]["Requirement"].ToString();
                    string factshuliang = dt_PurchaseInfo.Rows[i]["FactNumber"].ToString();
                    ws.Cells[startrows, startcols] = xuhao;
                    ws.Cells[startrows, startcols + 1] = diama.Replace("&nbsp;", "");
                    ws.Cells[startrows, startcols + 2] = pname;
                    ws.Cells[startrows, startcols + 3] = xinghaoguige;
                    ws.Cells[startrows, startcols + 4] = danwei;
                    ws.Cells[startrows, startcols + 5] = string.IsNullOrEmpty(factshuliang) ? xushuliang : factshuliang;
                    startrows++;
                    if (xuhao == maxnum)
                    {
                        startcols = 7;
                        startrows = startrows - maxnum;
                    }
                    if (xuhao == maxnum * 2) startcols = 1;
                }
            }
            dt_PurchaseInfo.Dispose();

            #endregion
        }

        private void AddTitle(Microsoft.Office.Interop.Excel._Worksheet ws, int rowsnum, string cid)
        {
            Microsoft.Office.Interop.Excel.Range canbie;//创建Range操作一行作为标题
            Catering_Model.Purchase md = new Catering_Rules.Purchase().GetModel(Convert.ToInt32(cid));

            #region 表头

            canbie = ws.get_Range(ws.Cells[rowsnum, 1], ws.Cells[rowsnum, 12]); //取得合并的区域
            canbie.MergeCells = true;//合并单元格 
            canbie = ws.get_Range(ws.Cells[rowsnum + 1, 1], ws.Cells[rowsnum + 1, 12]); //取得合并的区域
            canbie.MergeCells = true;//合并单元格 
            //canbie.HorizontalAlignment = XlVAlign.xlVAlignCenter;
            //ws.Cells[1, 1] = "采购计划";
            ws.Cells[rowsnum, 1] = "编号：" + md.RNo + "　　　　　　版本：" + md.Vs + "　　　　　　受控号：" + md.Controlled;
            ws.Cells[rowsnum + 1, 1] = "交货日期：" + md.Date.ToString("yyyy-MM-dd") + "　　　　　　交货地点：";
            canbie = ws.get_Range(ws.Cells[rowsnum, 1], ws.Cells[rowsnum + 1, 12]);//外围框设置
            canbie.BorderAround(1);

            #endregion

            #region 标题行

            for (int i = 0; i < 12; i++)
            {
                string cellName = "";
                switch (i % 6)
                {
                    case 0:
                        cellName = "序号";
                        break;
                    case 1:
                        cellName = "代码";
                        break;
                    case 2:
                        cellName = "产品名称";
                        break;
                    case 3:
                        cellName = "型号规格";
                        break;
                    case 4:
                        cellName = "单位";
                        break;
                    case 5:
                        cellName = "数量";
                        break;
                }
                ws.Cells[rowsnum + 2, i + 1] = cellName;
            }

            canbie = ws.get_Range(ws.Cells[rowsnum + 2, 1], ws.Cells[rowsnum + 2, 12]);
            canbie.Cells.HorizontalAlignment = XlVAlign.xlVAlignCenter;//文字居中
            canbie.Borders.LineStyle = 1;//边框设置

            #endregion
        }

        private void GetPuchase_Excel(Microsoft.Office.Interop.Excel._Worksheet ws, DataTable dt_PurchaseInfo, string typeName, string cid)
        {
            //Microsoft.Office.Interop.Excel._Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)book.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            Microsoft.Office.Interop.Excel.Range canbie;//创建Range操作一行作为标题            

            #region 表头

            Catering_Model.Purchase md = new Catering_Rules.Purchase().GetModel(Convert.ToInt32(cid));

            canbie = ws.get_Range(ws.Cells[1, 1], ws.Cells[1, 6]); //取得合并的区域
            canbie.MergeCells = true;//合并单元格 
            canbie = ws.get_Range(ws.Cells[2, 1], ws.Cells[2, 6]); //取得合并的区域
            canbie.MergeCells = true;//合并单元格 
            //canbie.HorizontalAlignment = XlVAlign.xlVAlignCenter;
            //ws.Cells[1, 1] = "采购计划";
            ws.Cells[1, 1] = "编号：" + md.RNo + "　　　版本：" + md.Vs + "　　　受控号：" + md.Controlled;
            ws.Cells[2, 1] = "交货日期：" + md.Date.ToString("yyyy-MM-dd") + "　　　交货地点：";
            canbie = ws.get_Range(ws.Cells[1, 1], ws.Cells[2, 6]);//外围框设置
            canbie.BorderAround(1);

            #endregion

            #region 标题行

            for (int i = 1; i < 7; i++)
            {
                string cellName = "";
                switch (i)
                {
                    case 1:
                        cellName = "序号";
                        break;
                    case 2:
                        cellName = "代码";
                        break;
                    case 3:
                        cellName = "产品名称";
                        break;
                    case 4:
                        cellName = "型号规格";
                        break;
                    case 5:
                        cellName = "单位";
                        break;
                    case 6:
                        cellName = "数量";
                        break;
                }
                ws.Cells[3, i] = cellName;
            }

            canbie = ws.get_Range(ws.Cells[3, 1], ws.Cells[3, 6]);
            canbie.Cells.HorizontalAlignment = XlVAlign.xlVAlignCenter;//文字居中
            canbie.Borders.LineStyle = 1;//边框设置



            #endregion

            #region 内容

            int starthang = 4;
            if (dt_PurchaseInfo != null && dt_PurchaseInfo.Rows.Count > 0)
            {
                for (int i = 0; i < dt_PurchaseInfo.Rows.Count; i++)
                {
                    int xuhao = i + 1;
                    string diama = this.Getpinhao(dt_PurchaseInfo.Rows[i]["DID"].ToString(), dt_PurchaseInfo.Rows[i]["CID"].ToString());
                    string pname = dt_PurchaseInfo.Rows[i]["PName"].ToString();
                    string xinghaoguige = this.GetRawGuiGe(dt_PurchaseInfo.Rows[i]["DID"].ToString());
                    string danwei = this.GetUnitName(dt_PurchaseInfo.Rows[i]["Company"].ToString());
                    string xushuliang = dt_PurchaseInfo.Rows[i]["Requirement"].ToString();
                    string factshuliang = dt_PurchaseInfo.Rows[i]["FactNumber"].ToString();
                    int temphang = starthang + i;
                    ws.Cells[temphang, 1] = xuhao;
                    ws.Cells[temphang, 2] = diama.Replace("&nbsp;", "");
                    ws.Cells[temphang, 3] = pname;
                    ws.Cells[temphang, 4] = xinghaoguige;
                    ws.Cells[temphang, 5] = danwei;
                    ws.Cells[temphang, 6] = string.IsNullOrEmpty(factshuliang) ? xushuliang : factshuliang;
                }
                starthang = starthang + dt_PurchaseInfo.Rows.Count;
            }
            dt_PurchaseInfo.Dispose();
            canbie = ws.get_Range(ws.Cells[4, 1], ws.Cells[starthang, 2]);
            canbie.HorizontalAlignment = XlVAlign.xlVAlignCenter;
            canbie = ws.get_Range(ws.Cells[4, 1], ws.Cells[starthang, 6]);

            #endregion

            #region 页面调整

            canbie.Borders.LineStyle = 1;
            ws.Cells.EntireColumn.AutoFit();//宽度自适应

            ws.PageSetup.CenterHeader = typeName + "采购计划";
            ws.PageSetup.LeftFooter = "编制人/日期：";
            ws.PageSetup.CenterFooter = "审核人/日期：";
            ws.PageSetup.RightFooter = "批准人:";
            ws.PageSetup.PrintTitleColumns = "$A:$F";

            ws.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlPortrait; //设置为纵向打印
            //ws.PageSetup.PaperSize = Microsoft.Office.Interop.Excel.XlPaperSize.xlPaperA4;       //设置打印字为A4纸张
            ws.PageSetup.PrintTitleRows = "$1:$3";
            //ws.PrintPreview(true);            //打印预览
            #endregion
        }

        /// <summary>
        /// 创建Excel表
        /// </summary>
        /// <returns></returns>
        public DataTable CreateExcelTable()
        {
            DataTable dt_new = new DataTable();
            dt_new.Columns.Add("CID", typeof(string));//增加字段CID
            dt_new.Columns.Add("DID", typeof(string));//增加字段DID
            dt_new.Columns.Add("PName", typeof(string));//增加字段PName
            dt_new.Columns.Add("Company", typeof(string));//增加字段Company
            dt_new.Columns.Add("Requirement", typeof(string));//增加字段Requirement
            dt_new.Columns.Add("FactNumber", typeof(string));//增加字段FactNumber
            return dt_new;
        }

        public Dictionary<int, string> GetRawMaterials()
        {
            Dictionary<int, string> dc = new Dictionary<int, string>();
            DataTable dt_RMID = new Catering_Rules.T_RawMaterials().GetAllList().Tables[0];
            if (dt_RMID != null && dt_RMID.Rows.Count > 0)
            {
                for (int i = 0; i < dt_RMID.Rows.Count; i++)
                {
                    int id = Convert.ToInt32(dt_RMID.Rows[i]["id"]);
                    string typename = dt_RMID.Rows[i]["TypeName"].ToString();
                    dc.Add(id, typename);
                }
                dt_RMID.Dispose();
            }
            return dc;
        }

        //导出食谱Excel
        public void Imp_Excel(DataSet ds)
        {
            string fileName = Guid.NewGuid().ToString() + ".xls";
            string path = "/" + Catering_DBOpertion.PubConstant.GetConfigValue("TempExcel");
            bool success = Catering.View_Operaction.DataSetToExcelHelper.DataSetToExcel(ds, path, false);

            if (!success)
                throw new Exception("Excel导出失败！");

            this.Response.AppendHeader("Content-Disposition", "attachment;filename=" + this.Server.UrlEncode(fileName));
            this.Response.ContentType = "application/ms-excel";

            System.IO.FileInfo file = new System.IO.FileInfo(path);
            long length = file.Length;

            Dictionary<int, int> fileDic = new Dictionary<int, int>();
            this.LoadDictionary(length, 1024, fileDic);

            for (int i = 0; i < fileDic.Count; i++)
            {
                int count = fileDic[i + 1];
                byte[] bytes = new byte[count];

                using (System.IO.FileStream fileStream = System.IO.File.OpenRead(path))
                {
                    fileStream.Seek(i * 1024, System.IO.SeekOrigin.Begin);
                    fileStream.Read(bytes, 0, bytes.Length);
                }

                this.Response.OutputStream.Write(bytes, 0, bytes.Length);
                this.Response.Flush();
            }
            this.Response.Close();

            System.IO.File.Delete(path);
        }

        private void LoadDictionary(long p, int blockMaxSize, Dictionary<int, int> dic)
        {
            if (p - blockMaxSize > 0)
            {
                dic.Add(dic.Count + 1, blockMaxSize);
                this.LoadDictionary(p - blockMaxSize, blockMaxSize, dic);
            }
            else if (p - blockMaxSize == 0)
            {
                dic.Add(dic.Count + 1, blockMaxSize);
                return;
            }
            else
            {
                dic.Add(dic.Count + 1, Int32.Parse(p.ToString()));
                return;
            }

        }

        //按照条件查询
        protected void btn_Search_Click(object sender, EventArgs e)
        {
            ViewState["Search"] = "1";
            this.AspNetPager1.CurrentPageIndex = 1;
            this.LoadRep(this.GetStrWhere());
        }

        //获取查询条件
        public string GetStrWhere()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("CID=" + Request.QueryString["CGID"].ToString());
            if (this.txt_Name.Text.Trim() != "")
            {
                sb.Append(" and PName like '%" + this.txt_Name.Text.Trim() + "%'");
            }
            return sb.ToString();
        }

        //获取可生成的菜谱
        [WebMethod]
        public static string GetRecipesByZD(string ClassID, string starttime, string endtime)
        {
            DataTable dt_Recipes = new Catering_Rules.T_Recipes().GetRecipesByInfo(ClassID, starttime, endtime).Tables[0];
            return GetRecipesHtml(dt_Recipes);
        }

        public static string GetRecipesHtml(DataTable dt)
        {
            StringBuilder sb = new StringBuilder();
            foreach (DataRow row in dt.Rows)
            {
                string zhouqi = GetZhouOptionByRid(row["id"].ToString());
                string selectid = "cbo" + row["id"].ToString();
                sb.Append("<tr><td><input type=\"checkbox\" name=\"ck\" value=\"" + row["id"].ToString() + "\" /></td>");
                sb.Append("<td>" + row["CateringName"].ToString() + "</td>");
                sb.Append("<td><select id='" + selectid + "' name='shipu_zouList'>" + zhouqi + "</select></td>");
                sb.Append("<td>" + Convert.ToDateTime(row["StateDate"]).ToString("yyyy-MM-dd") + "</td>");
                sb.Append("<td>" + Convert.ToDateTime(row["StopDate"]).ToString("yyyy-MM-dd") + "</td>");
                sb.Append("<td>" + row["Number"].ToString() + "</td></tr>");
            }
            return sb.ToString();
        }

        //获取可生成的采购计划
        [WebMethod]
        public static string GetRecipesByCG(string ClassID, string starttime, string endtime)
        {
            int zhouqi = (Convert.ToDateTime(endtime) - Convert.ToDateTime(starttime)).Days + 1;
            DataTable dt_Purchase = new Catering_Rules.Purchase().GetList("temp1='" + ClassID + "' and temp2 IS NOT NULL AND temp2<>'' ").Tables[0];
            return GetPurchaseHtml(dt_Purchase);
        }

        public static string GetPurchaseHtml(DataTable dt)
        {
            StringBuilder sb = new StringBuilder();
            foreach (DataRow row in dt.Rows)
            {
                sb.Append("<tr><td><input type=\"checkbox\" name=\"ck_Purchase\" value=\"" + row["id"].ToString() + "\" /></td>");
                sb.Append("<td>" + row["PPName"].ToString() + "</td>");
                sb.Append("<td>" + new Catering_Rules.T_Personnel().GetModel(Convert.ToInt32(row["URid"].ToString())).Name + "</td>");
                sb.Append("<td>" + row["EditDate"].ToString() + "</td>");
                sb.Append("<td>" + row["temp2"].ToString() + "</td></tr>");
            }
            return sb.ToString();
        }

        //自动生成采购计划
        [WebMethod]
        public static string AutoGenerate(string starttime, string endtime, string RecipesID, string CID, string weekTime)
        {
            string[] splitprecipes = RecipesID.TrimEnd(',').Split(',');
            string[] splitTime = weekTime.TrimEnd(',').Split(',');
            if (splitTime.Length == 0 || splitTime[0] == "") return "NO";
            string where1 = "";
            if (splitprecipes.Length > 0 && splitTime.Length > 0)
            {
                for (int i = 0; i < splitprecipes.Length; i++)
                {
                    string[] temptime = splitTime[i].Split('|');
                    if (i == 0)
                    {
                        starttime = temptime[0];
                        endtime = temptime[1];
                        where1 += " AND ((a.MID=" + splitprecipes[i] + " AND a.Date>=convert(datetime,'" + temptime[0] + "') AND a.Date<=convert(datetime,'" + temptime[1] + "')) ";
                        break;//只生成一个周期
                    }
                    else
                    {
                        where1 += " OR (a.MID=" + splitprecipes[i] + " AND a.Date>=convert(datetime,'" + temptime[0] + "') AND a.Date<=convert(datetime,'" + temptime[1] + "')) ";
                    }
                }
                where1 += ")";
            }
            //原料消耗总数
            DataTable dt_CaiGouCount = new Catering_Rules.T_Recipes().GetRecipesYLCount(where1).Tables[0];
            //每天每人消耗数
            DataTable dt_CaiGouDay = new Catering_Rules.T_Recipes().GetRecipesYLday(where1).Tables[0];

            DataTable dt_caigoujihua = GetCaiGouDt();

            #region 计算需要采购的原料
            if (dt_CaiGouCount != null && dt_CaiGouCount.Rows.Count > 0)
            {
                //更新采购周期
                int zhouqi = (Convert.ToDateTime(endtime) - Convert.ToDateTime(starttime)).Days + 1;
                new Catering_Rules.Purchase().UpdateByZouQi(Convert.ToInt32(CID), zhouqi);

                int i = 1;
                string PurchaseID = CID;
                string ClassID = new Catering_Rules.Purchase().GetModel(Convert.ToInt32(PurchaseID)).temp1;//班组ID
                foreach (DataRow row in dt_CaiGouCount.Rows)
                {
                    Catering_Model.E_RawMaterial md_RM = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(row["RawID"].ToString()));

                    DataRow r = dt_caigoujihua.NewRow();
                    r["id"] = i;
                    r["CID"] = PurchaseID;
                    r["DID"] = row["RawID"].ToString();
                    r["PName"] = md_RM.RAWName;
                    string strguige = "";
                    DataTable dt_guige = new Catering_Rules.RawMaterial_Unit().GetList("RawMaterialID=" + row["RawID"].ToString() + " ORDER BY ID ASC ").Tables[0];
                    decimal unit = 1;
                    bool flag = false;
                    string minid = "";
                    foreach (DataRow rowguige in dt_guige.Rows)
                    {
                        string UName = new Catering_Rules.Units().GetModel(Convert.ToInt32(rowguige["UnitID"].ToString())).UName;
                        if (minid == rowguige["UnitID"].ToString())
                        {
                            break;
                        }
                        else
                        {
                            minid = rowguige["UnitID"].ToString();
                        }
                        if (rowguige["Number"].ToString() != "")
                        {
                            strguige += rowguige["Number"].ToString() + UName + "*";
                            if (flag) unit = Convert.ToDecimal(rowguige["Number"]) * unit;
                            if (md_RM.temp2 == rowguige["UnitID"].ToString()) flag = true;
                        }
                    }
                    r["Specifications"] = strguige.TrimEnd('*');
                    r["Company"] = md_RM.temp2;//单位入库单位 int值

                    //需采购量
                    decimal YLCount = Convert.ToDecimal(row["content"].ToString()) / unit;
                    YLCount = YLCount / (md_RM.UsefulPart <= 0 ? 1 : (md_RM.UsefulPart / 100));
                    r["ProgramNumber"] = decimal.Round(YLCount, 2).ToString();

                    //剩余库存
                    decimal KuCount = 0;

                    //string strwhere = "ClassID=" + ClassID + " and RAWID=" + row["RawID"].ToString();//and DBID=1
                    //DataTable dt_KuCount = new Catering_Rules.InDbInfo().GetList(1, strwhere, "IntDate desc").Tables[0];
                    //decimal KuCount = 0;
                    //if (dt_KuCount != null && dt_KuCount.Rows.Count > 0)
                    //{
                    //    KuCount = Convert.ToDecimal(dt_KuCount.Rows[0]["temp1"].ToString());
                    //}
                    KuCount = new Catering_Rules.BalanceInfo().GetBalanceByRawID(Convert.ToInt32(ClassID), row["RawID"].ToString(), DateTime.Now);

                    //原料警戒线
                    string strwhere2 = "ClassID=" + ClassID + " and RAWID=" + row["RawID"].ToString();// and RoomID=1
                    DataTable dt_jingjie = new Catering_Rules.RoomWaing().GetList(strwhere2).Tables[0];
                    decimal Jingjie = 0;
                    if (dt_jingjie != null && dt_jingjie.Rows.Count > 0)
                    {
                        Jingjie = Convert.ToDecimal(dt_jingjie.Rows[0]["MinContent"].ToString());
                    }

                    //折损率
                    decimal zhesunl = string.IsNullOrEmpty(md_RM.temp1) ? 0 : Convert.ToDecimal(md_RM.temp1) / 100;

                    //可用量
                    decimal shengyul = KuCount - Jingjie;
                    decimal xuyao = decimal.Round(YLCount - shengyul, 2);
                    if (xuyao < 0) xuyao = 0;
                    //r["Requirement"] = xuyao;
                    r["Requirement"] = KuCount.ToString() == "0.00" ? 0 : KuCount;//原为：需要采购量，现为：库存结余（生成采购计划的当前时间）
                    //r["FactNumber"] = xuyao;
                    r["FactNumber"] = Toolss.GetMathResult(YLCount * (1 + zhesunl), 2, 3);//原为：实际采购量，现为：计划采购量*（1+折损率）
                    r["Back"] = "";
                    dt_caigoujihua.Rows.Add(r);
                    i++;
                }
            }
            #endregion

            //删除以前的生成
            new Catering_Rules.PurchaseInfo().DeleteByWhere(" CID=" + CID + " ");
            new Catering_Rules.PurchaseBydaily().DeleteListByWhere(" PurchaseID=" + CID + " ");

            AddCaiGouYL(dt_caigoujihua);

            //添加采购计划对应的每天没人需采购量，只是为了实现 采购模版生成
            if (dt_CaiGouDay != null && dt_CaiGouDay.Rows.Count > 0)
            {
                foreach (DataRow rowDay in dt_CaiGouDay.Rows)
                {
                    Catering_Model.PurchaseBydaily md = new Catering_Model.PurchaseBydaily();
                    md.id = new Catering_Rules.PurchaseBydaily().GetMaxId();
                    md.PurchaseID = Convert.ToInt32(CID);
                    md.RawID = Convert.ToInt32(rowDay["RawID"].ToString());
                    md.Number = rowDay["Content"].ToString();
                    new Catering_Rules.PurchaseBydaily().Add(md);
                }
            }
            //更新修改日期
            new Catering_Rules.Purchase().UpdateEditDate(DateTime.Now.ToString("yyyy-MM-dd"), CID);
            return "OK";
        }
        
        //添加采购计划
        public static void AddCaiGouYL(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow rowcaigou in dt.Rows)
                {
                    Catering_Model.PurchaseInfo md = new Catering_Model.PurchaseInfo();
                    md.id = new Catering_Rules.PurchaseInfo().GetMaxId();
                    md.CID = Convert.ToInt32(rowcaigou["CID"].ToString());
                    md.DID = rowcaigou["DID"].ToString();
                    md.PName = rowcaigou["PName"].ToString();
                    md.Specifications = rowcaigou["Specifications"].ToString();
                    md.Company = rowcaigou["Company"].ToString();
                    md.ProgramNumber = rowcaigou["ProgramNumber"].ToString();
                    md.Requirement = rowcaigou["Requirement"].ToString();
                    md.Back = rowcaigou["Back"].ToString();
                    md.FactNumber = rowcaigou["FactNumber"].ToString();
                    int rawid = 0;
                    decimal sum = 0;
                    Int32.TryParse(md.DID, out rawid);
                    decimal.TryParse(md.ProgramNumber, out sum);
                    if (rawid > 0)
                    {
                        Catering_Model.E_RawMaterial rm = new T_RawMaterial().GetModel(rawid);
                        if (rm != null)
                        {
                            string unit = new Catering_Rules.Units().GetModel(Convert.ToInt32(rm.temp2)).UName;
                            bool iskg = true;
                            decimal guige = 1;
                            decimal UtilKg = Toolss.GetSpecifications(rm.id, unit, out iskg);
                            guige = iskg ? 1000 : 1;
                            decimal weight = Toolss.GetMathResult(UtilKg * sum, 2, 3);
                            md.temp1 = (weight * guige).ToString();
                        }
                    }
                    new Catering_Rules.PurchaseInfo().Add(md);
                }
            }
        }

        //通过采购计划生成
        [WebMethod]
        public static string AutoGenerateByCG(string CountDay, string PurchaseID, string CID)
        {
            DataTable dt_caigou = new Catering_Rules.PurchaseBydaily().GetList("PurchaseID=" + PurchaseID).Tables[0];

            DataTable dt_caigoujihua = GetCaiGouDt();

            if (dt_caigou != null && dt_caigou.Rows.Count > 0)
            {
                int i = 1;
                string ClassID = new Catering_Rules.Purchase().GetModel(Convert.ToInt32(CID)).temp1;//班组ID
                foreach (DataRow row in dt_caigou.Rows)
                {
                    Catering_Model.E_RawMaterial md_RM = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(row["RawID"].ToString()));

                    DataRow r = dt_caigoujihua.NewRow();
                    r["id"] = i;
                    r["CID"] = CID;
                    r["DID"] = row["RawID"].ToString();
                    r["PName"] = md_RM.RAWName;
                    string strguige = "";
                    DataTable dt_guige = new Catering_Rules.RawMaterial_Unit().GetList("RawMaterialID=" + row["RawID"].ToString()).Tables[0];
                    decimal unit = 1;
                    bool flag = false;
                    string minid = "";
                    foreach (DataRow rowguige in dt_guige.Rows)
                    {
                        string UName = new Catering_Rules.Units().GetModel(Convert.ToInt32(rowguige["UnitID"].ToString())).UName;
                        if (minid == rowguige["UnitID"].ToString())
                        {
                            break;
                        }
                        else
                        {
                            minid = rowguige["UnitID"].ToString();
                        }
                        if (rowguige["Number"].ToString() != "")
                        {
                            strguige += rowguige["Number"].ToString() + UName + "*";
                            if (flag) unit = Convert.ToDecimal(rowguige["Number"]) * unit;
                            if (md_RM.temp2 == rowguige["UnitID"].ToString()) flag = true;
                        }
                    }
                    r["Specifications"] = strguige.TrimEnd('*');
                    r["Company"] = md_RM.temp2;//单位入库单位 int值

                    //需采购量
                    decimal YLCount = Convert.ToDecimal(row["Number"].ToString()) / unit * Convert.ToDecimal(CountDay);
                    YLCount = YLCount / (md_RM.UsefulPart <= 0 ? 1 : (md_RM.UsefulPart / 100));
                    r["ProgramNumber"] = decimal.Round(YLCount, 2).ToString();

                    //剩余库存

                    decimal KuCount = new Catering_Rules.BalanceInfo().GetBalanceByRawID(Convert.ToInt32(ClassID), row["RawID"].ToString(), DateTime.Now);

                    //原料警戒线
                    string strwhere2 = "ClassID=" + ClassID + " and RAWID=" + row["RawID"].ToString();// and RoomID=1
                    DataTable dt_jingjie = new Catering_Rules.RoomWaing().GetList(strwhere2).Tables[0];
                    decimal Jingjie = 0;
                    if (dt_jingjie != null && dt_jingjie.Rows.Count > 0)
                    {
                        Jingjie = Convert.ToDecimal(dt_jingjie.Rows[0]["MinContent"].ToString());
                    }
                    //decimal Jingjie = Convert.ToDecimal(new Catering_Rules.RoomWaing().GetList(strwhere2).Tables[0].Rows[0]["MinContent"].ToString());

                    //可用量
                    decimal shengyul = KuCount - Jingjie;
                    //折损率
                    decimal zhesunl = string.IsNullOrEmpty(md_RM.temp1) ? 0 : Convert.ToDecimal(md_RM.temp1) / 100;
                    //r["Requirement"] = (YLCount - shengyul) > 0 ? (YLCount - shengyul) : 0;
                    r["Requirement"] = KuCount.ToString() == "0.00" ? "0" : KuCount.ToString("G");
                    //r["FactNumber"] = (YLCount - shengyul) > 0 ? (YLCount - shengyul) : 0;
                    r["FactNumber"] = Toolss.GetMathResult(YLCount * (1 + zhesunl), 2, 3);
                    r["Back"] = "";

                    dt_caigoujihua.Rows.Add(r);
                    i++;
                }
            }
            //删除以前的生成
            new Catering_Rules.PurchaseInfo().DeleteByWhere(" CID=" + CID + " ");
            AddCaiGouYL(dt_caigoujihua);
            //更新修改日期
            new Catering_Rules.Purchase().UpdateEditDate(DateTime.Now.ToString("yyyy-MM-dd"), CID);
            return "OK";
        }

        //实例化采购知识表
        public static DataTable GetCaiGouDt()
        {
            DataTable dt_caigoujihua = new DataTable();
            dt_caigoujihua.Columns.Add("id");
            dt_caigoujihua.Columns.Add("CID");//采购ID
            dt_caigoujihua.Columns.Add("DID");//原料代码
            dt_caigoujihua.Columns.Add("PName");
            dt_caigoujihua.Columns.Add("Specifications");//型号规格=所有规格  累加
            dt_caigoujihua.Columns.Add("Company");
            dt_caigoujihua.Columns.Add("ProgramNumber");
            dt_caigoujihua.Columns.Add("Requirement");
            dt_caigoujihua.Columns.Add("Back");
            dt_caigoujihua.Columns.Add("FactNumber");
            return dt_caigoujihua;
        }

        //分页
        protected void AspNetPager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
        {
            this.AspNetPager1.CurrentPageIndex = e.NewPageIndex;
            if (ViewState["Search"] != null)
            {
                this.LoadRep(this.GetStrWhere());
            }
            else
            {
                this.LoadRep("CID=" + Request.QueryString["CGID"].ToString());
            }

        }

        //获取通过原料ID品号
        public string Getpinhao(string did, string cid)
        {
            if (string.IsNullOrEmpty(did)) return "&nbsp;";
            int pid = 0;
            Int32.TryParse(cid, out pid);
            if (pid <= 0) return "&nbsp;";
            Catering_Model.Purchase md_pur = new Catering_Rules.Purchase().GetModel(pid);
            if (md_pur == null) return "&nbsp;";
            Int32.TryParse(md_pur.temp1, out pid);
            if (pid <= 0) return "&nbsp;";
            Catering_Model.ClassInfo md_class = new Catering_Rules.ClassInfo().GetModel(pid);
            if (md_class == null) return "&nbsp;";
            string where = "RawID=" + did;
            switch (md_class.AreaID)
            {
                case 1:
                    where += " AND InDBid LIKE '1%'";
                    break;
                case 2:
                    where += " AND InDBid LIKE '2%'";
                    break;
                case 3:
                    where += " AND InDBid LIKE '3%'";
                    break;
                case 4:
                    where += " AND InDBid LIKE '4%'";
                    break;
            }

            DataTable dt = new Catering_Rules.RawMaterial_Area().GetList(where).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows[0]["InDBid"].ToString();
            }
            else
            {
                return "&nbsp;";
            }
        }

        //通过单位ID获取单位名称
        public string GetUnitName(string cid)
        {
            if (cid == "") return "&nbsp;";
            int id = 0;
            Int32.TryParse(cid, out id);
            if (id <= 0) return "&nbsp;";
            Catering_Model.Units md = new Catering_Rules.Units().GetModel(Convert.ToInt32(cid));
            return md != null ? md.UName : "&nbsp;";
        }

        //获取原料名称
        [WebMethod]
        public static ArrayList GetRawName(string pinghao)
        {
            ArrayList al = new ArrayList();
            if (!string.IsNullOrEmpty(pinghao))
            {
                DataTable dt_RawMaterial_Area = new Catering_Rules.RawMaterial_Area().GetList("InDBid='" + pinghao + "'").Tables[0];
                DataTable dt = new DataTable();
                if (dt_RawMaterial_Area != null && dt_RawMaterial_Area.Rows.Count > 0)
                {
                    dt = new Catering_Rules.T_RawMaterial().GetList("id=" + dt_RawMaterial_Area.Rows[0]["RawID"].ToString()).Tables[0];
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    al.Add("OK");
                    al.Add(dt.Rows[0]["RAWName"].ToString());
                    al.Add(new Catering_Rules.Units().GetModel(Convert.ToInt32(dt.Rows[0]["temp2"].ToString())).UName);
                    DataTable dt_RawMaterial_Unit = new Catering_Rules.RawMaterial_Unit().GetList("RawMaterialID=" + dt.Rows[0]["id"].ToString()).Tables[0];
                    if (dt_RawMaterial_Unit != null && dt_RawMaterial_Unit.Rows.Count > 0)
                    {
                        string str = "";
                        foreach (DataRow row in dt_RawMaterial_Unit.Rows)
                        {
                            Catering_Model.Units md = new Catering_Rules.Units().GetModel(Convert.ToInt32(row["UnitID"].ToString()));
                            str += row["Number"].ToString() + md.UName + "*";
                        }
                        al.Add(str);
                    }
                    else
                    {
                        al.Add("");
                    }
                    al.Add(dt.Rows[0]["temp2"].ToString());
                }
                else
                {
                    al.Add("NO");
                }
            }
            else
            {
                al.Add("NO");
            }
            return al;
        }

        //获取需采购量
        [WebMethod]
        public static string GetXCGNumber(string pinghao, string infoId, string Number)
        {
            string StrReturn = "";
            DataTable dt_RawMaterial_Area = new Catering_Rules.RawMaterial_Area().GetList("InDBid='" + pinghao + "'").Tables[0];
            if (dt_RawMaterial_Area != null && dt_RawMaterial_Area.Rows.Count > 0)
            {
                int RawID = Convert.ToInt32(dt_RawMaterial_Area.Rows[0]["RawID"].ToString());
                int ClassID = Convert.ToInt32(new Catering_Rules.Purchase().GetModel(Convert.ToInt32(infoId)).temp1);
                decimal DNumber = Convert.ToDecimal(Number);

                ArrayList alKCinfo = new Catering_Rules.BalanceInfo().GetLastBalanceInfo(ClassID.ToString(), RawID.ToString(), pinghao);
                if (alKCinfo != null && alKCinfo.Count > 0)
                {
                    string whereByRoomWaing = "ClassID=" + ClassID + " and RAWID=" + RawID;
                    DataTable dt_RoomWaing = new Catering_Rules.RoomWaing().GetList(whereByRoomWaing).Tables[0];
                    if (dt_RoomWaing != null && dt_RoomWaing.Rows.Count > 0)
                    {
                        decimal MinContent = Convert.ToDecimal(dt_RoomWaing.Rows[0]["MinContent"].ToString());
                        if ((Convert.ToDecimal(alKCinfo[1]) - MinContent) > 0)
                        {
                            if (Convert.ToDecimal(alKCinfo[1]) - MinContent - DNumber > 0)
                            {
                                StrReturn = "0";
                            }
                            else
                            {
                                StrReturn = decimal.Round(DNumber - (Convert.ToDecimal(alKCinfo[1]) - MinContent), 2).ToString();
                            }
                        }
                        else
                        {
                            StrReturn = decimal.Round(MinContent - Convert.ToDecimal(alKCinfo[1]) + DNumber, 2).ToString();
                        }
                    }
                    else
                    {
                        if ((Convert.ToDecimal(alKCinfo[1]) - DNumber) > 0)
                        {
                            StrReturn = "0";
                        }
                        else
                        {
                            StrReturn = decimal.Round(DNumber - Convert.ToDecimal(alKCinfo[1]), 2).ToString();
                        }
                    }
                }
                else
                {
                    StrReturn = DNumber.ToString();
                }

            }

            return StrReturn;
        }

        //获取原料规格
        public string GetRawGuiGe(string RawID)
        {
            int id = 0;
            if (string.IsNullOrEmpty(RawID)) return "";
            Int32.TryParse(RawID, out id);
            if (id <= 0) return "";
            string strguige = "";
            DataTable dt_guige = new Catering_Rules.RawMaterial_Unit().GetList("RawMaterialID=" + id).Tables[0];
            foreach (DataRow rowguige in dt_guige.Rows)
            {
                string UName = new Catering_Rules.Units().GetModel(Convert.ToInt32(rowguige["UnitID"].ToString())).UName;
                if (rowguige["Number"].ToString() != "")
                {
                    strguige += rowguige["Number"].ToString() + UName + "*";
                }
            }
            return strguige;
        }

        public string GetZheSunlv(string did)
        {
            Catering_Model.E_RawMaterial rm = GetRawMaterialInfo(did);
            if (rm != null && !string.IsNullOrEmpty(rm.temp1))
            {
                return rm.temp1 + "%";
            }
            return "&nbsp;";
        }

        public Catering_Model.E_RawMaterial GetRawMaterialInfo(string did)
        {
            if (string.IsNullOrEmpty(did)) return null;
            int id = 0;
            Int32.TryParse(did, out id);
            if (id <= 0) return null;
            Catering_Model.E_RawMaterial rm = new Catering_Model.E_RawMaterial();
            rm = new T_RawMaterial().GetModel(id);
            return rm;
        }

        protected void btn_FactNumberChange(object sender, EventArgs e)
        {
            string strid = this.hidid.Value;
            string factn = this.Change_FactNumber.Text.Trim();
            decimal num = 0;
            int id = 0;
            decimal.TryParse(factn, out num);
            Int32.TryParse(strid, out id);
            if (id > 0)
            {
                new PurchaseInfo().UpdateFactNumberByID(id.ToString(), num.ToString());
            }
            string url = GetCurrentUrl();
            Response.Redirect(url);
        }

        public string GetCurrentUrl()
        {
            string url = "caigou_Edit.aspx?CGID=" + Request.QueryString["CGID"].ToString();
            string searchtext = this.txt_Name.Text.Trim();
            if (!string.IsNullOrEmpty(searchtext))
            {
                url += "&SearchTxt=" + searchtext;
            }
            int page = this.AspNetPager1.CurrentPageIndex;
            if (page > 1)
            {
                url += "&page=" + page;
            }
            return url;
        }

        //通过食谱ID 获取周期
        public static string GetZhouOptionByRid(string Rid)
        {
            DataTable dt_Week = new Catering_Rules.T_RecipesWeek().GetList("RecipesID=" + Rid.ToString() + " order by Number").Tables[0];
            StringBuilder sb = new StringBuilder();
            if (dt_Week != null && dt_Week.Rows.Count > 0)
            {
                foreach (DataRow row in dt_Week.Rows)
                {
                    string startTime = Convert.ToDateTime(row["startDate"].ToString()).ToShortDateString();
                    string endTime = Convert.ToDateTime(row["endDate"].ToString()).ToShortDateString();
                    sb.Append("<option value=\"" + startTime + "|" + endTime + "\">" + row["temp1"].ToString() + "</option>");
                }
            }
            return sb.ToString();
        }
    }
}